<template>
  <div class="tags">
    <h3>标签</h3>
    <Spin v-if="loading" tip="加载中..." />
    <div v-else-if="error" class="error-message">{{ error }}</div>
    <div v-else-if="displayTags.length === 0" class="empty-state">暂无标签</div>
    <div v-else class="tag-list">
      <Tag v-for="tag in displayTags" :key="tag._id || tag.id" :color="color">
        <router-link :to="`/tag/${tag.id}`">{{ tag.name }}</router-link>
      </Tag>
    </div>
  </div>
</template>

<script setup>
import { defineProps, ref, onMounted, watch, computed } from 'vue'
import { Tag, Spin } from 'ant-design-vue'
import { useBlogStore } from '../stores/blog'

// 定义组件的属性
const props = defineProps({
  tags: {
    type: Array,
    required: false,
    default: () => []
  },
  color: {
    type: String,
    required: false,
    default: 'blue'
  },
  useApi: {
    type: Boolean,
    required: false,
    default: false
  }
})

// 使用 Pinia store
const blogStore = useBlogStore()

// 错误信息
const error = ref('')

// 获取标签数据
const fetchTags = async () => {
  if (!props.useApi) return
  
  error.value = ''
  
  try {
    await blogStore.getTags()
  } catch (err) {
    error.value = '获取标签失败: ' + (err.message || '未知错误')
  }
}

// 监听showInNav属性变化
watch(() => props.showInNav, () => {
  if (props.useApi) {
    fetchTags()
  }
}, { immediate: false })

// 组件挂载时获取数据
onMounted(() => {
  if (props.useApi) {
    fetchTags()
  }
})

// 计算最终显示的标签列表
const displayTags = computed(() => {
  return props.useApi ? blogStore.cachedTags : props.tags
})

// 计算加载状态
const loading = computed(() => {
  return props.useApi ? blogStore.isTagsLoading : false
})
</script>

<style scoped>
.tags {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  border: 1px solid rgba(0, 0, 0, 0.05);
  margin-bottom: 24px;
}

.tags h3 {
  margin: 0 0 16px 0;
  font-size: 1.1rem;
  font-weight: 600;
  color: #333;
  position: relative;
  padding-bottom: 8px;
}

.tags h3::after {
  content: '';
  position: absolute;
  left: 0;
  bottom: 0;
  width: 40px;
  height: 2px;
  background: linear-gradient(to right, #1890ff, #722ed1);
}

.tag-list {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.tag-list a {
  color: currentColor;
  text-decoration: none;
}

.tag-list a:hover {
  text-decoration: underline;
}

.ant-tag {
  cursor: pointer;
  transition: all 0.3s ease;
}

.ant-tag:hover {
  transform: translateY(-2px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.error-message {
  color: #ff4d4f;
  padding: 8px 0;
}

.empty-state {
  color: #999;
  padding: 8px 0;
}
</style>